Let's import the numpy
module.
import numpy as np
n = 5 # CHANGE ME
a1 = list(range(n)) # python list
a2 = np.arange(n) # numpy array
if n <= 10:
print(a1)
print(a2)
%timeit [i**2 for i in a1]
%timeit a2**2
Numpy Arrays: much less flexible, but:
a = np.array([1,2,3,5])
print(a)
print(a.dtype)
b = np.array([1.0,2.0,3.0])
print(b)
print(b.dtype)
But also noticed that:
c = np.array([1,2,3])
print(c)
print(c.dtype)
d = np.array([1,2.,3])
print(d)
print(d.dtype)
linspace
np.linspace(-1, 1, 9)
zeros
np.zeros((10,10), np.float64)
Create 2D arrays, using zeros, using reshape and from list
These propagate to all elements:
a = np.array([1.2, 3, 4])
b = np.array([0.5, 0, 1])
Addition, multiplication, power ... are all elementwise:
a+b
a*b
a**b
Numpy arrays have two (most) important attributes:
A = np.random.rand(5, 4, 3)
A.shape
The .shape
attribute contains the dimensionality array as a tuple. So the tuple (5,4,3)
means that we're dealing with a three-dimensional array of size $5 \times 4 \times 3$.
(numpy.random.rand
just generates an array of random numbers of the given shape.)
A.dtype
Other dtype
s include np.complex64
, np.int32
, ...
a = np.random.rand(5)
a.shape
a = np.array([2,3,5])
print(a)
print(a.shape)
a = np.array([[2],[3],[5]])
print(a)
print(a.shape)
a = np.array([[2,3,5]])
print(a)
print(a.shape)
We can change 1D numpy arrays into 2D numpy arrays using the function reshape
a = np.array([2,3,5]).reshape(3,1)
print(a)
print(a.shape)
a = np.array([2,3,5]).reshape(1,3)
print(a)
print(a.shape)
print(np.arange(1,10))
B = np.arange(1,10).reshape(3,3)
print(B)
print(B)
print(B.transpose())
print(B)
print(B.swapaxes(0,1))
print(B)
print(B.T)
print(B)
C = np.transpose(B)
print(C)
What happens when we try to take the transpose of 1D array?
a = np.array([[2,3,5]])
print(a.T)
But it works with 2D arrays
a = np.array([2,3,5]).reshape(3,1)
print(a)
print(a.T)
Matrix multiplication is np.dot(A, B)
for two 2D arrays.
A = np.random.rand(3, 2)
B = np.random.rand(2, 4)
C = np.dot(A,B)
print(C.shape)
b = np.array([5,6])
d = np.dot(A,b)
print(d.shape)
A = np.array([[1,3],[2,4]])
B = np.array([[2,1],[3,2]])
print(np.dot(A,B))
print(A@B)
a = np.array([1,2,3])
b = np.array([5,6,7])
#Inner Product
print(np.dot(a,b))
print(np.inner(a,b))
#Outer Product C[i,j] = a[i]*b[j]
C = np.outer(a,b)
print(np.shape(C))
print(C)